﻿using MCMesServer.DBFunctions.DBFuncs;
using MCMesServer.DBFunctions.TransformFuncs;
using MCMesServer.Model;
using MCMesServer.NetConnectFunc;
using MCMesServer.PublicLogInfo;
using MCMesServer.WorkMessageSaveFunc;
using MesDAL.DTO.ProcessSheet;
using System;
using System.Collections.Generic;
using System.Data.Entity.Validation;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MCMesServer.ServerReceiveFunctions.GenerateProcessSheet
{
    public class GenerateProcessSheetHandlerFunc
    {
        public static Dictionary<string, byte[]> num_image = new Dictionary<string, byte[]>();
        public static void HandleReceiveMsg(ServerModel model, IntPtr connId)
        {
            try
            {
                switch (model.Operation)
                {
                    case Operations.UploadWorkpiece:
                        ReceiveProcessFormMessage(model, connId);
                        break;
                    case Operations.UploadImageMsg:
                        ReceiveUploadImage(model, connId);
                        break;
                    case Operations.UploadProcessDetail:
                        ReceiveUploadProcessDetail(model, connId);
                        break;
                    default:
                        break;
                }
            }
            catch (Exception ex)
            {
                PublicLogInfoFunc.RecordManualErrorMessage($"[{model.Step}]发生接收错误，错误信息内容：{model.Message}", ex.ToString());
                return;
            }
        }

        #region 方法
        /// <summary>
        /// 接收工件信息
        /// </summary>
        /// <param name="model"></param>
        /// <param name="connId"></param>
        public async static void ReceiveProcessFormMessage(ServerModel model, IntPtr connId)
        {
            try
            {
                ProcessForm processForm = TransformModelFunc<ProcessForm>.TransformString2ModelFunc(model.Message);
                WorkpieceDTO workpiece = processForm.workpiece;
                List<ProcessSheetDTO> processList = processForm.processList;
                WorkpieceDTO addForm = await WorkPieceDBFunc.AddWorkPieceIntoDB(workpiece);
                List<ProcessSheetDTO> list = new List<ProcessSheetDTO>();
                if (!(processList is null))
                {
                    for (int i = 0; i < processList.Count; i++)
                    {
                        processList[i].workpiece = addForm;
                        list.Add(await ProcessSheetDBFunc.AddProcessList(processList[i]));
                    }
                }

                ServerModel serverModel = new ServerModel()
                {
                    MachineNum = model.MachineNum,
                    Step = model.Step,
                    Operation = model.Operation,
                    Message = model.Message
                };
                CommonConnectFunc.SendInterServerModelFunc(connId, serverModel);
            }
            catch (DbEntityValidationException ex)
            {
                CommonConnectFunc.SendServerError(connId, model.MachineNum, model.Operation, model.Step, ServerResCode.ERR_UnExpectOfState, ex.ToString());
                return;
            }
        }

        /// <summary>
        /// 接收上传来的工件图片
        /// </summary>
        /// <param name="model"></param>
        /// <param name="connId"></param>
        public static void ReceiveUploadImage(ServerModel model, IntPtr connId)
        {
            try
            {
                string[] arr = model.Message.Split(';');
                int pos = int.Parse(arr[2]);
                if (arr[0].Equals("Start"))
                {
                    if (num_image.ContainsKey(arr[1]))
                    {
                        num_image.Add(arr[1], new byte[1024 * 1024 * 100]);
                    }
                    else
                    {
                        num_image[arr[1]] = new byte[1024 * 1024 * 100];
                    }
                    Buffer.BlockCopy(model.Data, 0, num_image[arr[1]], pos, model.Data.Length);
                }
                else if (arr[0].Equals("Finish"))
                {
                    Buffer.BlockCopy(model.Data, 0, num_image[arr[1]], pos, model.Data.Length);
                    Image image = WorkPieceImageSaveFunc.ConvertByte2Image(num_image[arr[1]]);
                    WorkPieceImageSaveFunc.SaveImageIntoServer(arr[1], image);
                }
                else
                {
                    Buffer.BlockCopy(model.Data, 0, num_image[arr[1]], pos, model.Data.Length);
                }
                if (arr[0].Equals("Finish"))
                {
                    num_image.Remove(arr[1]);
                    ServerModel serverModel = new ServerModel()
                    {
                        MachineNum = model.MachineNum,
                        Step = model.Step,
                        Operation = model.Operation,
                        ResCode = ServerResCode.OPE_UploadImageSuccess,
                    };
                    serverModel.Message = arr[1];
                    CommonConnectFunc.SendInterServerModelFunc(connId, serverModel);
                }
            }
            catch (Exception ex)
            {
                CommonConnectFunc.SendServerError(connId, model.MachineNum, model.Operation, model.Step, ServerResCode.ERR_UnExpectOfState, ex.ToString());
                return;
            }
        }

        public async static void ReceiveUploadProcessDetail(ServerModel model, IntPtr connId)
        {
            try
            {
                ProcessForm form = TransformModelFunc<ProcessForm>.TransformString2ModelFunc(model.Message);

            }
            catch (Exception ex)
            {
                CommonConnectFunc.SendServerError(connId, model.MachineNum, model.Operation, model.Step, ServerResCode.ERR_UnExpectOfState, ex.ToString());
                return;
            }
        }
        #endregion
    }
}
